<template>
  <div class="shopping-cart">
    <el-card class="cart-container" v-loading="cartStore.Load">
      <template #header>
        <div class="cart-header">
          <h2>我的购物车</h2>
          <el-button type="primary" @click="handleClearCart" v-if="cartStore.cartItems?.length">清空购物车</el-button>
        </div>
      </template>

      <div v-if="!cartStore.cartItems?.length" class="empty-cart">
        <el-icon><ShoppingCart /></el-icon>
        <p>购物车还是空的哦~</p>
        <el-button type="primary" @click="goToHome">去逛逛</el-button>
      </div>

      <div v-else class="cart-content">
        <el-table 
          :data="cartStore.cartItems" 
          style="width: 100%" 
          @selection-change="cartStore.handleSelectionChange" 
          ref="tableRef"
        >
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column label="商品图片" width="180">
            <template #default="scope">
              <img :src="fileBaseUrl() + (scope.row.imageUrls ? scope.row.imageUrls.split(',')[0] : '')" class="product-image" />
            </template>
          </el-table-column>

          <el-table-column label="商品名称" prop="name">
            <template #default="scope">
              <div class="product-name">{{ scope.row.productName }}</div>
              <div class="product-desc">{{ scope.row.englishName }}</div>
            </template>
          </el-table-column>

          <el-table-column label="单价" width="120">
            <template #default="scope">
              <span class="price">¥{{ scope.row.price }}</span>
            </template>
          </el-table-column>

          <el-table-column label="数量" width="200">
            <template #default="scope">
              <el-input-number 
                v-model="scope.row.quantity" 
                :min="1" 
                :max="99" 
                size="small"
                @change="(value) => handleQuantityChange(scope.row.id, value)"
              ></el-input-number>
            </template>
          </el-table-column>

          <el-table-column label="小计" width="120">
            <template #default="scope">
              <span class="subtotal">¥{{ (scope.row.price * scope.row.quantity).toFixed(2) }}</span>
            </template>
          </el-table-column>

          <el-table-column label="操作" width="120">
            <template #default="scope">
              <el-button type="danger" class="delete-btn" @click="handleRemoveItem(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <div class="cart-footer">
          <div class="cart-summary">
            <span>已选择 {{ cartStore.selectedItems?.length || 0 }} 件商品</span>
            <span class="total-price">合计：¥{{ (cartStore.selectedTotalPrice || 0).toFixed(2) }}</span>
          </div>
          <el-button 
            type="primary" 
            size="large" 
            @click="checkout" 
            :disabled="!cartStore.selectedItems?.length"
          >结算</el-button>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ShoppingCart } from '@element-plus/icons-vue'
import { useCartStore } from '@/stores/cartStore'
import { fileBaseUrl } from '@/apis/files'

const router = useRouter()
const tableRef = ref(null)
const cartStore = useCartStore()

// 获取用户信息
const user = JSON.parse(localStorage.getItem("user")?.userInfo || '{}')

// 初始化购物车数据
onMounted(async () => {
  try {
    await cartStore.fetchCartItems(user.userId)
  } catch (error) {
    ElMessage.error('获取购物车数据失败')
  }
})

// 处理数量更新
const handleQuantityChange = async (id, quantity) => {
  try {
    const res = await cartStore.updateItemQuantity(id, quantity)
    if (res.code === '0') {
      ElMessage.success('更新成功')
      await cartStore.fetchCartItems(user.userId)
    } else {
      ElMessage.error(res.msg)
    }
  } catch (error) {
    ElMessage.error('更新失败，请稍后重试')
  }
}

// 处理删除商品
const handleRemoveItem = async (id) => {
  try {
    await ElMessageBox.confirm('确定要删除这个商品吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const res = await cartStore.deleteCartItem(id)
    if (res.code === '0') {
      ElMessage.success('删除成功')
      await cartStore.fetchCartItems(user.userId)
    } else {
      ElMessage.error(res.msg)
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败，请稍后重试')
    }
  }
}

// 处理清空购物车
const handleClearCart = async () => {
  try {
    await ElMessageBox.confirm('确定要清空购物车吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const res = await cartStore.clearAllItems()
    if (res.code === '0') {
      ElMessage.success('购物车已清空')
      await cartStore.fetchCartItems(user.userId)
    } else {
      ElMessage.error(res.msg)
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('清空购物车失败，请稍后重试')
    }
  }
}

// 处理全选/取消全选
const handleSelectAll = (val) => {
  if (val) {
    tableRef.value?.toggleAllSelection()
  } else {
    tableRef.value?.clearSelection()
  }
}

const checkout = () => {
  if (!cartStore.selectedItems?.length) {
    ElMessage.warning('请选择要结算的商品')
    return
  }
  // 格式化商品数据
  const checkoutItems = cartStore.selectedItems.map(item => ({
    productId: item.productId,
    photographerId: item.photographerId,
    productName: item.productName,
    englishName: item.englishName,
    price: item.price,
    imageUrls: item.imageUrls,
    quantity: item.quantity
  }))
  localStorage.setItem('checkoutItems', JSON.stringify(checkoutItems))
  router.push('/checkout')
}

const goToHome = () => {
  router.push('/')
}
</script>

<style scoped>
.shopping-cart {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 60px);
}

.cart-container {
  max-width: 1200px;
  margin: 0 auto;
}

.cart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.cart-header h2 {
  margin: 0;
  color: #303133;
}

.empty-cart {
  text-align: center;
  padding: 40px 0;
}

.empty-cart i {
  font-size: 60px;
  color: #909399;
}

.empty-cart p {
  color: #909399;
  margin: 20px 0;
}

.product-image {
  width: 100px;
  height: 100px;
  object-fit: cover;
  border-radius: 4px;
}

.product-name {
  font-size: 16px;
  color: #303133;
  margin-bottom: 8px;
}

.product-desc {
  font-size: 14px;
  color: #909399;
}

.price,
.subtotal {
  color: #f56c6c;
  font-weight: bold;
}


.cart-footer {
  margin-top: 20px;
  padding: 20px;
  background-color: #f8f9fa;
  border-radius: 4px;
  display: flex;
  justify-content: flex-end;
  align-items: center;
}

.cart-summary {
  margin-right: 20px;
  display: flex;
  align-items: center;
  gap: 20px;
}

.cart-summary span {
  margin-right: 20px;
  color: #606266;
}

.total-price {
  font-size: 18px;
  color: #f56c6c;
  font-weight: bold;
}
</style>
